import React, {createRef, memo, useCallback, useEffect} from 'react';
import {LoginWrapper} from "./style";
import {initLoginBG} from "@/utils/login_bg";

import {Form, Input, Button, message} from 'antd';
import {UserOutlined, LockOutlined} from '@ant-design/icons';
import {userLogin} from "@/network/user.request";
// import eventBus from "@/utils/eventBus";
import {changeAdminUserAction} from "@/store/admin/actionCreators";
import {useDispatch} from "react-redux";

export default memo(function Login(props) {

  const canvasRef = createRef();
  const dispatch = useDispatch();

  useEffect(() => {
    canvasRef.current && initLoginBG(canvasRef.current)
  }, [canvasRef])

  const onFinish = useCallback(async (obj) => {
    const {nickname, password} = obj;
    const key = 'login-key';
    if (nickname.length >= 1 && nickname.length <= 10 && password.length >= 5 && password.length <= 20) {
      message.loading({content: '正在登录...', key});
      const user = await userLogin(nickname, password);
      if (user) {
        message.destroy(key);
        localStorage.setItem("admin-user", JSON.stringify(user));
        props.history.push(`/admin/home/u/${user.id}`);
        dispatch(changeAdminUserAction(user));
        // eventBus.emit("entry", user.id);
      } else {
        message.error({content: '用户名/密码不正确的说~', key, duration: 2});
      }
    }
  }, [dispatch, props.history])

  return (
    <LoginWrapper>
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
      >
        <Form.Item
          name="nickname"
          rules={[
            {
              required: true,
              message: '请输入你的用户名',
            }
          ]}
        >
          <Input size="large" prefix={<UserOutlined className="site-form-item-icon"/>} placeholder="请输入用户名"/>
        </Form.Item>
        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: '请输入你的密码',
            },
          ]}
        >
          <Input size="large" prefix={<LockOutlined className="site-form-item-icon"/>} type="password"
                 placeholder="输入密码"/>
        </Form.Item>

        <Form.Item>
          <Button type="primary" size="large" htmlType="submit" className="login-form-button px-7">
            登录
          </Button>
        </Form.Item>
      </Form>
      <canvas ref={canvasRef} id="snow-flake-app"></canvas>
    </LoginWrapper>
  )
})